#include <jni.h>
#include <GLES3/gl3.h>
#include <android_utility.h>
#include "gles_utility.h"

#ifdef __cplusplus
extern "C" {
#endif

static GLuint program;

void createV1() {
    char vShaderStr[] =
            "#version 300 es                          \n"
            "layout(location = 0) in vec4 vPosition;  \n"
            "void main()                              \n"
            "{                                        \n"
            "   gl_Position = vPosition;              \n"
            "}                                        \n";
    char fShaderStr[] =
            "#version 300 es                              \n"
            "precision mediump float;                     \n"
            "out vec4 fragColor;                          \n"
            "void main()                                  \n"
            "{                                            \n"
            "   fragColor = vec4 ( 1.0, 0.0, 0.0, 1.0 );  \n"
            "}                                            \n";
    program = glesInitialize(vShaderStr, fShaderStr);
    glClearColor(1.0F, 1.0F, 1.0F, 0.0F);
}

void createV2(JNIEnv *env, jobject assetManager) {
    char vBuf[512] = {};
    glesGetTextForAsset(env, assetManager, "vertex/vertex_sample_triangle_v2.essl", vBuf);
    char fBuf[512] = {};
    glesGetTextForAsset(env, assetManager, "fragment/fragment_sample_triangle_v2.essl", fBuf);
    program = glesInitialize(vBuf, fBuf);
    glesLogIntegerv(program, "a_position");
    glClearColor(0.0F, 0.0F, 0.0F, 0.0F);
}

void drawV1() {
    GLfloat vVertices[] = {
            0.0F, 0.5F, 0.0F,
            -0.5F, -0.5F, 0.0F,
            0.5F, -0.5F, 0.0F,
    };
    glClear(GL_COLOR_BUFFER_BIT);
    glUseProgram(program);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, vVertices);
    glEnableVertexAttribArray(0);
    glDrawArrays(GL_TRIANGLES, 0, 3);
}

void drawV2() {
    GLfloat vertexPos[] = {
            0.0F, 0.5F, 0.0F,
            -0.5F, -0.5F, 0.0F,
            0.5F, -0.5F, 0.0F,
    };
    glClear(GL_COLOR_BUFFER_BIT);
    glUseProgram(program);
    // 这里的第一个参数1对应vShaderStr的'location = 0'中的属性索引1
    glVertexAttrib4f(0, 1.0F, 0.0F, 0.0F, 1.0F);
    // 这里的第一个参数1对应vShaderStr的'location = 1'中的属性索引1
    glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, vertexPos);
    // 这里的参数1对应vShaderStr的'location = 1'中的属性索引1
    glEnableVertexAttribArray(1);
    glDrawArrays(GL_TRIANGLES, 0, 3);
    glDisableVertexAttribArray(1);
}

JNIEXPORT void JNICALL
Java_com_andova_egl_Triangle_00024Companion_surfCreated(JNIEnv *env, jobject,
                                                        jobject assetManager) {
    createV2(env, assetManager);
}

JNIEXPORT void JNICALL
Java_com_andova_egl_Triangle_00024Companion_surfChanged(JNIEnv *, jobject, jint w, jint h) {
    glViewport(0, 0, w, h);
}

JNIEXPORT void JNICALL
Java_com_andova_egl_Triangle_00024Companion_drawFrame(JNIEnv *, jobject) {
    drawV2();
}

#ifdef __cplusplus
}
#endif